package com.skywolf.chem.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.skywolf.chem.article.entity.LiveInfo;
import com.skywolf.chem.common.config.data.DataSource;
import com.skywolf.chem.common.config.data.DataSourceNames;
import com.skywolf.chem.common.sysconfig.pojo.vo.PageVO;
import com.skywolf.chem.common.sysconfig.utils.IpUtils;
import com.skywolf.chem.manager.entity.*;
import com.skywolf.chem.manager.service.ActivityService;
import com.skywolf.chem.match.common.enums.MatchPayTypeEnum;
import com.skywolf.chem.match.common.page.PageInfo;
import com.skywolf.chem.match.entity.*;
import com.skywolf.chem.match.mapper.*;
import com.skywolf.chem.match.pay.alibaba.service.AliPayRefundService;
import com.skywolf.chem.match.pay.wx.service.PayRefundService;
import com.skywolf.chem.match.service.IGroupInfoService;
import com.skywolf.chem.match.service.ISponsorService;
import com.skywolf.chem.match.utils.LocalAddress;
import com.skywolf.chem.utils.SysConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by pei_pei on 2021/9/26.
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<MatchInfoMapper, Info> implements ActivityService {

    private static final Logger logger = LoggerFactory.getLogger(IpUtils.class);

    @Autowired
    MatchInfoMapper matchInfoMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ISponsorService sponsorService;

    @Autowired
    IGroupInfoService groupInfoService;

    @Autowired
    SponsorMapper sponsorMapper;

    @Autowired
    TypeMapper typeMapper;

    @Autowired
    ApplyUserRecordMapper recordMapper;

    @Autowired
    PayRefundService payRefundService;

    @Autowired
    AliPayRefundService aliPayRefundService;

    @Override
    @DataSource(DataSourceNames.TWO)
    public PageVO<ActivityVo> getActivityList(ActivityParam queryParam) {
        Long startNum = queryParam.getPageSize()*(queryParam.getPageNum()-1);
        Long endNum = queryParam.getPageSize();
        Integer count = matchInfoMapper.getActivityCountManager(queryParam.getMatchName(),queryParam.getMatchStatus(),queryParam.getApplyStatus(),queryParam.getStartTime(),queryParam.getEndTime());
        List<ActivityVo> list = matchInfoMapper.getActivityListManager(startNum,endNum,queryParam.getMatchName(),queryParam.getMatchStatus(),queryParam.getApplyStatus(),queryParam.getStartTime(),queryParam.getEndTime());
        for (ActivityVo item:list) {
            List<ActivitySponsorVo> sponsor = sponsorMapper.getUserCount(item.getId());
            item.setSponsor(sponsor);
        }
        PageVO<ActivityVo> pageVO = new PageVO<>(list, Long.valueOf(count), queryParam.getPageNum(), queryParam.getPageSize());
        return pageVO;
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public List<Type> getActivityTypeList() {
        QueryWrapper<Type> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        return typeMapper.selectList(queryWrapper);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    @DataSource(DataSourceNames.TWO)
    public void addActivity(ActivityRequest request) throws Exception {
        Info info = request.getInfo();
        info.setDeleted(false);
        List<Sponsor> sponsor = request.getSponsor();
        List<GroupInfo> groupInfo = request.getGroupInfo();

        //新增
        if(info.getId()==null || info.getId()==0 ){
            String addr = info.getAddress()+info.getAddressDetail();
            Map<String,String> local = LocalAddress.getLocal(addr);
            info.setLongitude(local.get("longitude"));
            info.setLatitude(local.get("latitude"));
            info.setCreatedTime(LocalDateTime.now());
            matchInfoMapper.insert(info);
        }else{
            Info infoOld = matchInfoMapper.selectById(info.getId());
            if(!infoOld.getAddress().equalsIgnoreCase(info.getAddress()) || !infoOld.getAddressDetail().equalsIgnoreCase(info.getAddressDetail())){
                String addr = info.getAddress()+info.getAddressDetail();
                Map<String,String> local = LocalAddress.getLocal(addr);
                info.setLongitude(local.get("longitude"));
                info.setLatitude(local.get("latitude"));
                info.setCreatedTime(LocalDateTime.now());
            }
            //修改
            groupInfoService.delGroupInfo(info.getId());
            sponsorService.delSponsorByMatchId(info.getId());

            matchInfoMapper.updateById(info);
        }
        for (Sponsor item:sponsor) {
            item.setMatchId(info.getId());
            item.setDeleted(false);
        }
        sponsorService.saveBatch(sponsor);

        for (GroupInfo item:groupInfo) {
            item.setMatchId(info.getId());
            item.setDeleted(false);
        }
        groupInfoService.saveBatch(groupInfo);
    }

    @Override
    public void delActivity(Long id) {
        UpdateWrapper<Info> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        this.remove(updateWrapper);
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public void applyActivity(ActivityApplyRequest request) {
        Info info = matchInfoMapper.selectById(request.getId());
        info.setId(request.getId());
        info.setMatchStatus(request.getMatchStatus());
        info.setApplyStr(request.getApplyStr());
        this.updateById(info);
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public ActivityRequest getActivityInfo(Long id) {
        ActivityRequest result = new ActivityRequest();
        Info info = this.getById(id);
        result.setInfo(info);

        List<Sponsor> sponsor = sponsorService.list(new QueryWrapper<Sponsor>()
                .eq("match_id",id)
                .orderByDesc("id"));
        result.setSponsor(sponsor);

        List<GroupInfo> groupInfo = groupInfoService.list(new QueryWrapper<GroupInfo>()
                .eq("match_id",id)
                .orderByDesc("id"));
        result.setGroupInfo(groupInfo);

        return result;
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public PageVO<ActivityRecordVo> getUserList(ActivityRecordRequest pageParam) {
        Page<ActivityRecordVo> page = new PageInfo<>(pageParam);
        IPage<ActivityRecordVo> iPage = matchInfoMapper.getUserList(page, pageParam);
        return new PageVO<ActivityRecordVo>(iPage);
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public void applyActivityUser(ActivityApplyUserRequest request) throws ServiceException {
        ApplyUserRecord old = recordMapper.selectById(request.getId());
        if(old==null){
            throw new ServiceException("报名记录不存在");
        }
        if(request.getApplyStatus()==102){
            Order order = orderMapper.selectById(old.getMatchOrderId());
            if(order==null){
                logger.error("applyActivityUser error data:{}", JSON.toJSONString(request));
                throw new ServiceException("订单不存在");
            }
            try{
                if(order.getPayType()== MatchPayTypeEnum.WX_JSAPI.getType()){
                    payRefundService.wxPayRefund(old.getMatchOrderId(),request.getId());
                }
                if(order.getPayType()==2){
                    aliPayRefundService.wxPayRefund(old.getMatchOrderId(),request.getId());
                }
            }catch (Exception e){
                logger.error("applyActivityUser send:{},error:{}", JSON.toJSONString(request),e);
                throw new ServiceException("支付通道退款异常");
            }
        }
        old.setId(request.getId());
        old.setApplyStatus(request.getApplyStatus());
        old.setBackStr(request.getApplyStr());
        recordMapper.updateById(old);
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public ActivityUserInfoResponse getActivityUserInfo(Long id) {
        ActivityUserInfoResponse result = new ActivityUserInfoResponse();
        ApplyUserRecord record = recordMapper.selectById(id);
        Info info = matchInfoMapper.selectById(record.getMatchId());
        if(record!=null){
            ActivityUserInfoVo user = new ActivityUserInfoVo();
            BeanUtils.copyProperties(record,user);
            //用户自定义属性为空，证明没填写，获取match_info的自定义字段格式展示
            List<CustomItemVo> items =  JSONArray.parseArray(record.getOtherInfoJson(),CustomItemVo.class);
            if(items==null || items.size()==0){
                items =  JSONArray.parseArray(info.getApplyUserCustomTag(),CustomItemVo.class);
            }
            user.setItems(items);
            result.setUser(user);

            ActivityGroupVo group = new ActivityGroupVo();
            GroupInfo groupInfo =  groupInfoService.getById(record.getMatchGroupId());
            if(groupInfo!=null){
                BeanUtils.copyProperties(groupInfo,group);
            }
            List<CustomItemVo> customItems =  JSONArray.parseArray(info.getCustomTag(),CustomItemVo.class);
            group.setCustomItems(customItems);
            result.setGroup(group);
            return result;
        }
        return null;
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public List<ReportUserListVo> getReportUserList(String activityName) {
        List<ReportUserListVo> iPage = matchInfoMapper.getReportUserList(activityName);
        return iPage;
    }

    @Override
    @DataSource(DataSourceNames.TWO)
    public List<Type> getActivityTypeListTest() {
        QueryWrapper<Type> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        return typeMapper.selectList(queryWrapper);
    }

}
